//*****************************************************************************
// File Name	: main.c
//
// Title		: app
// Revision		: 1.0
// Notes		:
// Target MCU	: Atmel AVR atmega88 series
// Editor Tabs	: 4
//
// Revision History:
// When			Who					Description of change
// -----------	-----------	-----------------------
// 24-Jun-2010	Eugene Korneev		Created the program
//*****************************************************************************




#include "global.h"			//		глобальные определения,
							//		io.h, interrupt.h, eeprom.h, boot.h, pgmspace.h
							//		port.h

#include "main.h"			//		определения и библиотечные	инклуды (	lib_crc16.h,
							//												lib_eeprom.h,
							//												lib_timer.h,
							//												lib_uart.h


// Redirect all unused interrupts to reti
EMPTY_INTERRUPT( __vector_default );
extern void __ctors_end(void) __attribute__((__noreturn__));
// macros for entering subprograms
#define __JMP_INIT__ __asm__ __volatile__ ("rjmp __ctors_end" )



//static USHORT   usTimerOCRADelta;


//STEE* const EEMEM EE;	// еепром сейчас 320 (256+64)



MODBUS_t EEMEM EEA;


/* ----------------------- Defines ------------------------------------------*/





/* ----------------------- Static variables ---------------------------------*/


int main ( void )
{
	///CHAR *zzzzzz="1234567890";
	//const char* xxx="I wanna fuck U now!!!";
	//uint8_t f, al;

	//uint8_t *p_f  = (uint8_t *) &EEA.F[0];
	//uint8_t *p_al = (uint8_t *) &EEA.A[0].byte.lo;


	//uint8_t val2[7] = {0x99,0x98,0x97,0x96,0x95,0x94,0x00};
	//USHORT	a;
	//a=usMBCRC16(val2,6);

	//f  = eeprom_read_byte ( p_f);
	//al  = eeprom_read_byte ( p_al);

	//initEEPROM(EEA);

	//eeprom_write_byte ( p_f, 0x55);


	//char	MSEL = MSELREAD;

	//eeprom_write_byte ( p_f, MSEL);

	//DDRD |= 1<<DDRD3;
	//DDRD &= ~(1<<2);

	//LED_OFF;
	//if (MSEL) LED_ON;

	//while (1) {
		//MSEL = MSELREAD;
		//if (MSEL==4) LED_ON;
		//if (MSEL==0) LED_OFF;
	//};






	//modbus -------------------------------------------------
	//eMBErrorCode    eStatus;									//	Error Code
	//eStatus = eMBInit ( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );	//	Инициализируем
    //eStatus = eMBSetSlaveID ( 0x34, TRUE, ucSlaveID, 3 );		//	Выставляем Slave ID#
	SerialInit(0,MB_PAR_NONE);
    sei();



    /* Enable the Modbus Protocol Stack. */
	//eStatus = eMBEnable();
    //SerialEnable (TRUE,TRUE);


//  SerialPutByte( 'H' );
//	SerialPutByte( 'e' );
//	SerialPutByte( 'l' );
//	SerialPutByte( 'l' );
//	SerialPutByte( 'o' );


    //SerialSendFrame( zzzzzz, (u16)5 );

//    const UCHAR     ucSlaveID[] = { 0xAA, 0xBB, 0xCC };
    //eMBErrorCode    eStatus;

    //eStatus = eMBSetSlaveID( 0x34, TRUE, ucSlaveID, 3 );

    //const UCHAR     reply[] = { 0x00, 0x13, 0x00, 0x0A, 0x02, 0xCD, 0x01 };
    const UCHAR     reply[] = { 0x00, 0x02, 0x00, 0x05 };

    SerialSendFrame ((UCHAR) 0x01, (UCHAR) 0x03, (UCHAR*)reply, (USHORT) 4 );



    while(1) {
    //	( void )eMBPoll(  );
    	//usRegHoldingBuf[0]++;
    }


	//initEEPROM(EE);
//	uartInit();
//	uartSetBaudRate(9600);
//	uartSendByte('Z');
	return TRUE;
}

// сразу после сброса
void __init(void) __attribute__((naked));
void __init(void)								// проверим память и т.п. (это до инициализации стека ...)
{
    cli();			//	нет прерываниям
    //ERROR_INIT;		//	гасим свет)))
    //FLAG_INIT;

    //LED_OFF;
    //FLAG_OFF;
    //ERROR_OFF;

//    volatile register uint8_t *data =  (uint8_t*)0; //__attribute__((section(".data")));			//	указатель на начало секции .data (RAM)
//	volatile register uint8_t fill = 0x55;															//	константа заполнителя...

	//sei();

//	for( register uint16_t i=RAMSTART; i<=RAMEND; i++)												//	тестим RAM + заполняем ее 55 AA 55 AA.....
//    {
//    	data[i] = fill;
//    	if( data[i] != fill )
//    	{
    		//ERROR_ON;
//    		while(1);
//    		break;
//    	}
//    	fill=~fill;
//    	data[i] = fill;
//    	if( data[i] != fill )
//        {
    		//ERROR_ON;
//    		while(1);
//    		break;
//    	}
//    }

//	LED_INIT;
//	LED_OFF;

	//MCUCR |= (1<<IVCE);		// Enable change of interrupt vectors
	//MCUCR |= (1<<IVSEL);	// Move interrupts to boot flash section
//	MCUCR = (1<<IVCE);
//	MCUCR = (1<<IVSEL);

    //waiting for external devices to be ready then continue program flow
    //while( (PINC&_BV(PC0)) == 1 );

    // because function is marked as “naked” then after each “}” initialization	jumps to following program.
    // If there is need to set up __zero_reg__ and stack pointer, then go to standard point of calling macro program
    __JMP_INIT__;
}





// Following program will be placed just after __zero_reg__ ans stack pointer initialization
void init3(void) __attribute__((section(".init3"))) __attribute__((naked));
void init3(void)
{
	//LED_OFF;
	//InitInt();

    LED_INIT;
    LED_OFF;

	TimerInit();
	TimerEnable();


	//InitWD();

    //DDRB = 0xFF;
    //PORTB = 0xFF;
    //DDRD = 0xFF;
    //PORTD = 0;


}

//void	TimerExpired(void){
//	static int aaa=0;
//	static int bbb=0;

//	if (aaa++==50000) {
//		aaa=0;
//		bbb++;
//		ERROR_ON;
//	}


//}

